package com.funtl.itoken.web.posts.interceptor;

import com.funtl.itoken.common.domain.TbSysUser;
import com.funtl.itoken.common.utils.CookieUtils;
import com.funtl.itoken.common.utils.MapperUtils;
import com.funtl.itoken.common.web.constants.WebConstants;
import com.funtl.itoken.common.web.utils.HttpServletUtils;
import com.funtl.itoken.web.posts.service.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class WebPostsIntorceptor implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;

    @Value("${hosts.sso}")
    private String host_sso;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否登录
        String token = CookieUtils.getCookieValue(request, WebConstants.TOKEN);
        // token 没有内容，一定没有登录
        if(StringUtils.isBlank(token)){

            response.sendRedirect(String.format("%s/login?url=%s", host_sso, HttpServletUtils.getFullPath(request)));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        TbSysUser tbSysUser = (TbSysUser) session.getAttribute(WebConstants.SESSION_USER);
        // 已登录
        if(tbSysUser!=null){
            if(modelAndView!=null){
                modelAndView.addObject(tbSysUser);
            }
        }else{
            // 未登录

            String token = CookieUtils.getCookieValue(request, WebConstants.TOKEN);
            if(StringUtils.isNotBlank(token)){
                String loginCode = redisService.get(token);
                if(StringUtils.isNotBlank(loginCode)){
                    String json = redisService.get(loginCode);
                    tbSysUser= MapperUtils.json2pojo(json, TbSysUser.class);
                    // 已登录
                    request.getSession().setAttribute(WebConstants.SESSION_USER, tbSysUser);
                    if(modelAndView!=null){
                        modelAndView.addObject(tbSysUser);
                    }
                }

            }
        }

    //    二次确认是否有用户信息
        if(tbSysUser==null){
            response.sendRedirect("http://localhost:8503/login?url=http://localhost:8601");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
